<template>
    <form @submit.prevent="handleSubmit">
        <slot></slot>
    </form>
</template>

<script>

export default {
    name: 'Form',
    props:{
        onSubmit:{
            type: Function,
            default: () => {}
        }
    },
    provide(){
        return {
            getFormItemData: this.getFormItemData,
            getFormItemInstance: this.getFormItemInstance
        }
    },
    data(){
        return {
            formData:{},
            formInstances:{}
        }
    },
    methods:{
        async handleSubmit(){
            try {
                await this.validateForm()
                this.onSubmit && this.onSubmit(this.formData)
            } catch (error) {
                console.log(error);
            }
        },
        getFormItemData(key,value){
            this.formData[key] = value
        },
        getFormItemInstance(key,instance){
            this.formInstances[key] = instance
        },
        async validateForm(){
            for (const key of Object.keys(this.formInstances)) {
                if(!key) continue
                const res = await this.formInstances[key].__vue__.validate(this.formData[key])
                if(!res){
                    return Promise.reject()
                }
            }
            return Promise.resolve()
        }
    }
}
</script>
